import axios from 'axios';

class OpenAIClient {
    constructor(apiKey = import.meta.env.VITE_OPENAI_API_KEY, 
                baseURL = import.meta.env.VITE_OPENAI_BASE_URL, 
                model = import.meta.env.VITE_OPENAI_MODEL) {
        if (!apiKey) {
            throw new Error('API_KEY is required, please provide it as a parameter or set VITE_OPENAI_API_KEY in .env file');
        }

        this.client = axios.create({
            baseURL,
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }
        });
        this.model = model || 'gpt-3.5-turbo';
    }

    async chat(messages, options = {}) {
        if (!Array.isArray(messages)) {
            throw new Error('Messages must be an array');
        }
        
        try {
            const response = await this.client.post('/chat/completions', {
                model: this.model,
                messages,
                ...options
            });
            return response.data.choices[0].message.content;
        } catch (error) {
            console.error('OpenAI chat error:', error);
            throw error;
        }
    }
}

export default OpenAIClient;